import React, { useState, useEffect } from 'react'
import { Search, FilePlus, Folder, File, Settings, Clock, ChevronLeft, ChevronRight } from 'lucide-react'
import { FileInfo } from '../types/electron'

interface GitSidebarProps {
  files: FileInfo[]
  currentFile: string | null
  onFileSelect: (filePath: string) => void
  onNewFile: () => void
  onSaveFile: () => void
  onOpenFile: () => void
  onSettings: () => void
  isCollapsed?: boolean
  onToggleCollapse?: () => void
}

// FileItem interface 已移除，不再需要

const GitSidebar: React.FC<GitSidebarProps> = ({
  files,
  currentFile,
  onFileSelect,
  onNewFile,
  onSaveFile,
  onOpenFile,
  onSettings,
  isCollapsed = false,
  onToggleCollapse
}) => {
  const [searchQuery, setSearchQuery] = useState('')
  // 只保留最近文件标签页，移除重复的文件功能
  const [recentFiles, setRecentFiles] = useState<FileInfo[]>([])

  useEffect(() => {
    // Load recent files from electron store
    const loadRecentFiles = async () => {
      try {
        if (window.electronAPI?.getRecentFiles) {
          const recent = await window.electronAPI.getRecentFiles()
          // 确保按打开时间降序排序（最新的在前面）
          const sortedRecent = recent.sort((a, b) => b.openedTime - a.openedTime)
          setRecentFiles(sortedRecent)
        }
      } catch (error) {
        console.error('Failed to load recent files:', error)
      }
    }

    loadRecentFiles()

    // 设置定时器定期刷新最近文件列表
    const interval = setInterval(loadRecentFiles, 5000) // 每5秒刷新一次

    return () => clearInterval(interval)
  }, [])

  // Git相关功能已移除，专注于最近文件功能

  const filteredRecentFiles = recentFiles.filter(file =>
    file.path && file.path.toLowerCase().includes(searchQuery.toLowerCase())
  )

  const handleFileSelect = (filePath: string) => {
    onFileSelect(filePath)
  }

  const handleNewFile = () => {
    onNewFile()
  }

  // Git提交查看功能已移除

  // renderFileItem 函数已移除，不再需要

  // Git commit rendering 功能已移除，专注于最近文件功能

  return (
    <div className={`${isCollapsed ? 'w-12' : 'w-64'} bg-gray-50 dark:bg-gray-900 border-r border-gray-200 dark:border-gray-700 flex flex-col h-full transition-all duration-300`}>
      {/* Header */}
      <div className="p-4 border-b border-gray-200 dark:border-gray-700">
        {!isCollapsed ? (
          <>
            <div className="flex items-center justify-between mb-4">
              <h1 className="text-lg font-semibold text-gray-900 dark:text-gray-100">
                IntelliMark
              </h1>
              <button
                onClick={onToggleCollapse}
                className="p-2 hover:bg-gray-200 dark:hover:bg-gray-700 rounded-lg transition-colors"
                title="收起侧边栏"
              >
                <ChevronLeft className="w-4 h-4 text-gray-600 dark:text-gray-400" />
              </button>
            </div>

            {/* File Action Buttons */}
            <div className="flex items-center space-x-2 mb-4">
              <button
                onClick={handleNewFile}
                className="flex-1 flex items-center justify-center px-3 py-2 bg-blue-500 hover:bg-blue-600 text-white rounded-lg transition-colors font-medium text-sm"
                title="新建文件"
              >
                <FilePlus className="w-4 h-4" />
              </button>
              <button
                onClick={onOpenFile}
                className="flex-1 flex items-center justify-center px-3 py-2 bg-gray-100 dark:bg-gray-800 hover:bg-gray-200 dark:hover:bg-gray-700 text-gray-700 dark:text-gray-300 rounded-lg transition-colors font-medium text-sm border border-gray-300 dark:border-gray-600"
                title="打开文件"
              >
                <Folder className="w-4 h-4" />
              </button>
              <button
                onClick={onSaveFile}
                className="flex-1 flex items-center justify-center px-3 py-2 bg-green-100 dark:bg-green-900/30 hover:bg-green-200 dark:hover:bg-green-900/50 text-green-700 dark:text-green-400 rounded-lg transition-colors font-medium text-sm border border-green-300 dark:border-green-700"
                title="保存文件"
              >
                <File className="w-4 h-4" />
              </button>
            </div>

            {/* Search */}
            <div className="relative">
              <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-gray-400" />
              <input
                type="text"
                placeholder="搜索文件..."
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                className="w-full pl-10 pr-4 py-2 bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 text-sm"
              />
            </div>
          </>
        ) : (
          <div className="flex flex-col items-center space-y-3">
            <button
              onClick={onToggleCollapse}
              className="p-2 hover:bg-gray-200 dark:hover:bg-gray-700 rounded-lg transition-colors"
              title="展开侧边栏"
            >
              <ChevronRight className="w-4 h-4 text-gray-600 dark:text-gray-400" />
            </button>
            {/* New File Button */}
            <button
              onClick={handleNewFile}
              className="p-2 hover:bg-gray-200 dark:hover:bg-gray-700 rounded-lg transition-colors"
              title="新建文件"
            >
              <FilePlus className="w-4 h-4 text-gray-600 dark:text-gray-400" />
            </button>
            
            {/* Open File Button */}
            <button
              onClick={onOpenFile}
              className="p-2 hover:bg-gray-200 dark:hover:bg-gray-700 rounded-lg transition-colors"
              title="打开文件"
            >
              <File className="w-4 h-4 text-gray-600 dark:text-gray-400" />
            </button>
            
            {/* Save File Button */}
            <button
              onClick={onSaveFile}
              className="p-2 hover:bg-gray-200 dark:hover:bg-gray-700 rounded-lg transition-colors"
              title="保存文件"
            >
              <svg className="w-4 h-4 text-gray-600 dark:text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 7H5a2 2 0 00-2 2v9a2 2 0 002 2h14a2 2 0 002-2V9a2 2 0 00-2-2h-3m-1 4l-3-3m0 0l-3 3m3-3v12" />
              </svg>
            </button>
          </div>
        )}
      </div>

      {/* Section Header */}
      {!isCollapsed && (
        <div className="flex border-b border-gray-200 dark:border-gray-700 px-4 py-2">
          <h2 className="text-sm font-medium text-gray-700 dark:text-gray-300 flex items-center">
            <Clock className="w-4 h-4 mr-2" />
            最近文件
          </h2>
        </div>
      )}

      {/* Content */}
      {!isCollapsed && (
        <div className="flex-1 overflow-y-auto">
          <div className="p-2">
            {filteredRecentFiles.length > 0 ? (
              filteredRecentFiles.map((fileInfo, index) => (
                <div
                  key={`recent-${fileInfo.path || `file-${fileInfo.openedTime}-${index}`}`}
                  onClick={() => handleFileSelect(fileInfo.path)}
                  className={`file-tree-item flex items-center px-3 py-2 cursor-pointer hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg ${
                    currentFile === fileInfo.path ? 'bg-blue-50 dark:bg-blue-900/20' : ''
                  }`}
                  title={`${fileInfo.path}\n打开时间: ${new Date(fileInfo.openedTime).toLocaleString()}`}
                >
                  <Clock className="w-4 h-4 text-gray-500 mr-3 flex-shrink-0" />
                  <div className="flex-1 min-w-0">
                    <div className="text-sm text-gray-700 dark:text-gray-300 truncate">
                      {fileInfo.path.split('/').pop()}
                    </div>
                    <div className="text-xs text-gray-500 dark:text-gray-400 truncate">
                      {fileInfo.path}
                    </div>
                  </div>
                </div>
              ))
            ) : (
              <div className="p-4 text-center text-gray-500 dark:text-gray-400 text-sm">
                暂无最近文件
              </div>
            )}
          </div>
        </div>
      )}

      {/* Footer */}
      <div className="p-3 border-t border-gray-200 dark:border-gray-700">
        <button
          onClick={onSettings}
          className="w-full flex items-center justify-center px-3 py-2 text-sm text-gray-600 dark:text-gray-400 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition-colors"
          title="设置"
        >
          <Settings className="w-4 h-4" />
        </button>
      </div>
    </div>
  )
}

export default GitSidebar